package com.ccx.mytemplate.controller;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccx.mytemplate.entity.MyRecords;
import com.ccx.mytemplate.mapper.MyRecordsMapper;
import com.ccx.mytemplate.util.ExcelUtil;
import com.ccx.mytemplate.util.HttpUtil;
import com.ccx.mytemplate.util.Res;
import com.ccx.mytemplate.util.WordUtil;

import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

@RestController
@RequestMapping("/myRecords")
public class MyRecordsController {

    @Autowired
    private MyRecordsMapper myRecordsMapper;

    @RequestMapping("/page")
    public Res page(@RequestParam(defaultValue = "1") Integer pageNum, 
                            @RequestParam(defaultValue = "10") Integer pageSize, String title) {
        Page<MyRecords> page = Page.of(pageNum, pageSize);
        page.addOrder(OrderItem.descs("update_time"));
        LambdaQueryWrapper<MyRecords> query = Wrappers.lambdaQuery();
        query.like(title != null && title.length() > 0, MyRecords::getTitle, title);
        IPage<MyRecords> res = myRecordsMapper.selectPage(page, query);
        return Res.success(res);
    }

    @RequestMapping("/save")
    public Res save(@RequestBody MyRecords myRecords) {
        boolean success = myRecordsMapper.insertOrUpdate(myRecords);
        return Res.success(success);
    }

    @RequestMapping("/delete")
    public Res delete(Integer id) {
        int res = myRecordsMapper.deleteById(id);
        return Res.success(res);
    }

    @RequestMapping("/export")
    public void export(HttpServletResponse response) throws Exception {
        List<MyRecords> list = myRecordsMapper.selectList(Wrappers.lambdaQuery());
        List<String> headers = List.of("创建时间", "更新时间", "创建用户", "更新用户", "标题", "内容", "手机号");
        List<?> dats = list.stream().map(record -> Arrays.asList(
            record.getCreateTime(),
            record.getUpdateTime(),
            record.getCreateUser(),
            record.getUpdateUser(),
            record.getTitle(),
            record.getContent(),
            record.getPhone()
        )).toList();
        HttpUtil.setExcelResponseHeaders(response, "test.xlsx");
        ExcelUtil.exportExcel(headers, (List<List<Object>>) dats, response.getOutputStream());
    }

    @RequestMapping("/import")
    public Res importExcel(@RequestParam("file") Part file) throws Exception {
        List<String> headers = List.of("标题", "内容", "手机号");
        List<java.util.Map<String, Object>> data = ExcelUtil.excel2Data(file.getInputStream(), headers);
        List<MyRecords> records = data.stream().map(map -> {
            MyRecords record = MyRecords.builder()
                .createUser("test")
                .updateUser("test")
                .title(String.valueOf(map.get("标题")))
                .content(String.valueOf(map.get("内容")))
                .phone(String.valueOf(map.get("手机号")))
                .build();
            return record;
        }).toList();
        myRecordsMapper.insert(records);
        return Res.success(records.size());
    }

    @RequestMapping("exportStatistics")
    public void exportWord(HttpServletResponse response) throws Exception {
        Long dataSum = myRecordsMapper.selectCount(null);
        List<Map<String,Object>> incrementEveryHourToday = myRecordsMapper.getIncrementEveryHourToday();
        List<Map<String,Object>> incrementEveryDay = myRecordsMapper.getIncrementEveryDay(7);
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("dataSum", dataSum);
        dataMap.put("今日数据增长趋势", Map.of(
            "cats", incrementEveryHourToday.stream().map(i -> i.get("ch").toString()).toList(),
            "vals", incrementEveryHourToday.stream().map(i -> i.get("ct").toString()).toList()
        ));
        dataMap.put("近7日数据增长趋势", Map.of(
            "cats", incrementEveryDay.stream().map(i -> i.get("cd").toString()).toList(),
            "vals", incrementEveryDay.stream().map(i -> i.get("ct").toString()).toList()
        ));
        HttpUtil.setWordResponseHeaders(response, "记录统计.docx");
        
        try (XWPFDocument doc = WordUtil.data2Word(dataMap, "/static/记录统计.docx");) {
            doc.write(response.getOutputStream());
        }
    }
}
